<template>
  <a-page-header
    style="border: 1px solid rgb(235, 237, 240); margin-bottom: 10px"
    :title="paperInfo.name"
    :sub-title="paperInfo.caption"
  >
    <template #tags>
      <a-tag color="blue">正在考试</a-tag>
    </template>
    <template v-slot:extra>
      <a-button key="2" @click="visible = true">选择题目</a-button>
      <a-button key="1" @click="submitExamClick" type="danger">提交试卷</a-button>
    </template>
    <a-descriptions>
      <a-descriptions-item label="考生姓名">{{ userInfo.name }}</a-descriptions-item>
      <a-descriptions-item label="考生学号">{{ userInfo.stuNumber }}</a-descriptions-item>
    </a-descriptions>
    <a-row type="flex">
      <a-statistic-countdown title="剩余时间" :value="deadline" style="margin-right: 50px" @finish="onFinish" />
    </a-row>
  </a-page-header>
  <a-row type="flex" justify="center" style="margin-top: 30px">
    <a-col :span="16">
      <question-card
        v-if="questionList != null"
        @onChangeQuestion="changeQuestion"
        :question="questionList[selectedIndex]"
        :questionId="selectedIndex"
        :answer="answers[selectedQuestion.id]"
        @onAnswerChange="handleAnswerChange"
      />
    </a-col>
  </a-row>
  <a-drawer title="选择题目" placement="right" v-model:visible="visible">
    <a-select v-model:value="selectedIndex" style="width: 100%">
      <a-select-option v-for="(item, index) in questionList" :key="index" :value="index">
        <template v-if="answers[item.id] == null || answers[item.id].length == 0">未做 题目 {{ index + 1 }}</template>
        <template v-else>已做 题目 {{ index + 1 }}</template>
      </a-select-option>
    </a-select>
  </a-drawer>
</template>

<script>
import { message, Modal } from "ant-design-vue";
import { computed, createVNode, defineComponent, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getExamQuestion,
  getExamStatus,
  getLoginUser,
  restoreAnswer,
  saveExamAnswer,
  startExam,
  submitExam,
} from "../../utils/api";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import QuestionCard from "../../components/exam/QuestionCard.vue";

export default defineComponent({
  setup() {
    // vue router
    const route = useRoute();
    const router = useRouter();
    const examId = route.params["examId"];
    // 考试信息
    const paperInfo = reactive({
      name: "",
      caption: "",
    });
    const userInfo = ref({
      id: 0,
      name: "",
      password: null,
      stuNumber: "",
    });

    const visible = ref(false);
    const answers = reactive({});
    const selectedIndex = ref(0);
    const questionList = ref();
    const deadline = ref(Date.now() + 1000 * 60 * 60 * 24 * 2 + 1000 * 30);

    const selectedQuestion = computed(() => {
      return questionList.value?.[selectedIndex.value];
    });
    watch(selectedQuestion, (value, oldValue) => {
      if (oldValue != undefined) {
        saveAnswer(oldValue.id);
      }
    });

    const changeQuestion = (num) => {
      if (selectedIndex.value + num >= 0 && selectedIndex.value + num < questionList.value.length) {
        selectedIndex.value += num;
      }
    };
    const saveAnswer = async (questionId) => {
      let answerQuestion = questionList.value.filter((value) => value.id === questionId)[0];
      if (answerQuestion.isSave) {
        return;
      }
      if (answers[questionId] == null || answers[questionId].length == 0) {
        return;
      }
      let result = await saveExamAnswer({
        examId,
        questionId,
        answer: [].concat(answers[questionId]),
      });
      message.success(result.data.message);
      answerQuestion.isSave = true;
    };
    const handleAnswerChange = (answer) => {
      // 打上未保存标记
      selectedQuestion.value.isSave = false;
      answers[selectedQuestion.value.id] = answer;
    };
    const handleRestoreAnswer = async () => {
      let answerResult = await restoreAnswer(examId);
      answerResult = answerResult.data.data;
      answerResult.forEach((element) => {
        let answerQuestion = questionList.value.filter((e1) => {
          return e1.id === element.questionId;
        })[0];
        answerQuestion.isSave = true;
        let qType = answerQuestion.type;
        let answerObj = JSON.parse(element.answer);
        if (qType == 1 || qType == 3) {
          answers[element.questionId] = answerObj[0];
        } else if (qType == 2) {
          answers[element.questionId] = answerObj;
        }
      });
    };
    const handleSubmitExam = () => {
      submitExam(examId).then((res) => {
        message.success(res.data.message);
        toFinish();
      });
    };
    const toFinish = () => {
      router.push({ name: "ExamFinish", params: { examId } });
    };
    const submitExamClick = () => {
      Modal.confirm({
        title: "是否要提交试卷?",
        icon: createVNode(ExclamationCircleOutlined),
        content: "请检查所有题目是否完成",
        async onOk() {
          await saveAnswer(selectedQuestion.value.id);
          handleSubmitExam();
        },
      });
    };
    const onFinish = async () => {
      message.error("考试结束，已为您自动交卷1");
      await saveAnswer(selectedQuestion.value.id);
      handleSubmitExam();
    };

    const handleStartExam = async () => {
      let result = await startExam(examId);
      // 如果不能开始考试,则返回登录页面
      if (result.data.code != 200) {
        message.error(result.data.message);
        router.push({ name: "LoginExam", params: { examId } });
        return false;
      }
      // 开始考试成功,设置考试结束时间
      deadline.value = result.data.data.endTime * 1000;
      return true;
    };
    const fetchExamInfo = async () => {
      let loginUserResult = await getLoginUser();
      userInfo.value = loginUserResult.data.data;
      let examQuestionsResult = await getExamQuestion(examId);
      message.success(examQuestionsResult.data.message);
      questionList.value = examQuestionsResult.data.data.questionList;
      paperInfo.name = examQuestionsResult.data.data.name;
      paperInfo.caption = examQuestionsResult.data.data.caption;
    };
    const initExam = async () => {
      let examStatusResult = await getExamStatus(examId);
      if (examStatusResult.data.code != 200) {
        // 这个时候用户应该是未考试状态,调用接口让其参加考试
        message.error(examStatusResult.data.message);
        let startExamResult = await handleStartExam();
        if (!startExamResult) {
          return;
        }
      } else {
        // 获取状态成功,说明用户已经开始考试
        let examStatusData = examStatusResult.data.data;
        if (examStatusData.status === 1) {
          message.error("考试已结束");
          toFinish();
          return;
        }
        if (parseInt(examStatusData.endTime) < parseInt(Date.now() / 1000)) {
          message.error("考试已结束,已自动为您提交试卷");
          handleSubmitExam();
          return;
        }
        deadline.value = examStatusData.endTime * 1000;
      }
      await fetchExamInfo();
      await handleRestoreAnswer();
    };

    onMounted(initExam);
    return {
      userInfo,
      paperInfo,
      deadline,
      questionList,
      selectedIndex,
      answers,
      selectedQuestion,
      visible,
      changeQuestion,
      handleAnswerChange,
      handleRestoreAnswer,
      handleSubmitExam,
      submitExamClick,
      onFinish,
    };
  },
  components: { QuestionCard },
});
</script>
